<?php

require_once 'BaseObject.php';
require_once 'Services.php';
/**
 * Controller loader
 */
class Nanoframe extends BaseObject {
	protected static $instance = null;
	protected $baseUrl;
	protected function __construct() {
		$this->baseUrl = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1);
		$svcLdr = Services::getInstance();
		$svcLdr->load();
	}
	public function getInstance() {
		if(null === self::$instance) {
			self::$instance = new self();
		}
		return self::$instance;
	}
	public function root() {
		return $this->baseUrl;
	}
	public function handleException($e){
		$conf = $this->config();
		if($conf['debug']) {
			echo '<h1>'.$e->getCode().'</h1>';
			echo '<h2>'.$e->getMessage().'</h2>';
			echo '<p><b>File:</b> '.$e->getFile().'</p>';
			echo '<p><b>Line:</b> '.$e->getLine().'</p>';
			echo '<pre>'.$e->getTraceAsString().'</pre>';
		} else {
			ob_end_clean();
			@header('HTTP/1.1 404 Not Found');
			exit;
		}
		exit;
	}
	public function runCtrl() {
		$route = end($this->signal()->emit('route', $_GET['__q']));
		$ctrl = @$route['ctrl'];
		$act = @$route['act'];
		if(!@$route['params']) { $params = array(); }
		$params = array_merge_recursive($params, $_REQUEST);
		
		$ctrlFileName = 'ctrl/'.$ctrl.'Ctrl.php';
		$ctrlName = $ctrl.'Ctrl';
		if(file_exists($ctrlFileName)){
			if(is_readable($ctrlFileName)) {
				require_once($ctrlFileName);
				if(class_exists($ctrlName)) {
					$ctrlObj = new $ctrlName();
					if(!$act) {
						$act = 'Index';
					}
					$actName = 'act'.$act;
					if(method_exists($ctrlObj, $actName)) {
						$ctrlObj->$actName($params);
						$ctrlObj->postAction($actName);
					} else {
						throw new Exception ('Action not found', 404);
					}
				} else {
					throw new Exception ('Controller class not found', 500);
				}
			} else {
				throw new Exception ('Controller file not readable', 500);
			}
		} else {
			throw new Exception ('Controller not found', 404);
		}
	}
}
